package com.store.app.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.MainActivity;
import com.store.app.activity.TheOrderActivity;
import com.store.app.activity.WebViewHYDActivity;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.bean.EventBusBean;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Ben
 * on 2016/8/8 0008.\
 */
public class PayUtil implements AlipayState {
    private String money;
    private String info;
    private String title;
    private String dataStr;
    private Context mContext;
    private GoToLogin goToLogin;
    private TextView tv_yuer;
    public static String payment_id;
    public static String tid;
    private String dataSource;
    private String seller;
    private String buyer;
    private String orderType;
    private String return_url;

    public PayUtil(TextView tv_yuer, String money, Context context,String tid,String payment_id,String title,String info,String dataSource,String seller,String buyer,String orderType,String return_url) {
        this.money = money;
        mContext = context;
        this.tv_yuer = tv_yuer;
        this.payment_id = payment_id;
        this.info = info;
        this.title = title;
        this.tid = tid;
        this.dataSource = dataSource;
        this.seller = seller;
        this.orderType = orderType;
        this.buyer = buyer;
        this.return_url = return_url;
        WebViewHYDActivity.return_url_wc = return_url;
        Log.v("zyl", "传递过来了：" + return_url);
        goToLogin = new GoToLogin(context);
//        mContext.registerReceiver(myReceiver, new IntentFilter("FINISH"));
    }

    @Override
    public void onAlipaySuccess() {
        Log.v("zyl", "支付宝支付成功");

        if(!TextUtils.isEmpty(return_url)){
            EventBus.getDefault().post(new EventBusBean(211,return_url));
        }


        if (mContext instanceof Activity)
            ((Activity) mContext).finish();
        EventBus.getDefault().post(new CouponGoCashBean(1));


    }

    @Override
    public void onAlipayFail() {
        Log.v("zyl", "支付宝支付失败");
//        goBackToHYD("2",tid,payment_id);
        if(!TextUtils.isEmpty(return_url)){
            EventBus.getDefault().post(new EventBusBean(211,return_url+"?is_success=F"));
        }
    }

    public void startGetOrder(String type) {
        new GetOrder(type).start();
    }


    /**
     * 订单支付接口
     */
    public class GetOrder extends Thread {
        private String payWay;

        public GetOrder(String payWay) {
            this.payWay = payWay;
        }

        public void run() {
            try {
                JSONObject params = new JSONObject();
                Log.v("zyl","return_url:"+return_url);
                if(!TextUtils.isEmpty(return_url)){
                    params.put("return_url",return_url);
                }

                params.put("data_source",dataSource);     // 数据来源
                params.put("out_trade_no", payment_id);     //订单号
                params.put("detail", title);
                params.put("amount", money);                      // 交易金额
                //支付宝支付方式  "ZFFS_01"
                params.put("payment_way_key", payWay);                          //支付方式
                params.put("buyer_id", buyer);                 //店东的id
                params.put("seller_id", seller);         //每天惠的id
                       //支付宝跟微信
                params.put("order_type_key", orderType);
                Log.v("zy;","提交之前的："+params.toString());
                JSONObject params2 = new JSONObject();
                params2.put("payment_id", payment_id);
                params2.put("money", money);
                params2.put("title", title);
                params2.put("tid", tid);
                params2.put("stores_id", buyer);
                params2.put("payment_way_key", payWay);
                //订单类型
                params.put("out_trade_body", params2.toString());

                List<NameValuePair> pairList = new ArrayList<NameValuePair>();
                pairList.add(new BasicNameValuePair("params", params.toString()));
                pairList.add(new BasicNameValuePair("service", "finance.orderPay"));
                pairList.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(pairList);
                pairList.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(pairList, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");

                if (rsp_code.equals("succ")) {
                    dataStr = obj.getString("data");
                    Log.v("zyl", "订单支付成功:" + dataStr);
                    if (payWay.equals(SettingData.PAYMENT_WAY_01)) {
                        AlipayModel   model = new AlipayModel();
                        model.json2Model(dataStr);
                        handler.obtainMessage(1,model).sendToTarget();
                    } else if(payWay.equals(SettingData.PAYMENT_WAY_02)){
                        WXOrderbean  wxOrderbean = new WXOrderbean();
                        JSONObject object = new JSONObject(dataStr);
                        wxOrderbean.setTransaction_no(object.getString("transaction_no"));
                        wxOrderbean.setTimestamp(object.getString("timestamp"));
                        wxOrderbean.setSign(object.getString("sign"));
                        wxOrderbean.setPartnerid(object.getString("partnerid"));
                        wxOrderbean.setPackageX(object.getString("package"));
                        wxOrderbean.setNoncestr(object.getString("noncestr"));
                        wxOrderbean.setAppid(object.getString("appid"));
                        wxOrderbean.setPrepayid(object.getString("prepayid"));

                        handler.obtainMessage(4,wxOrderbean).sendToTarget();
                    }else if (payWay.equals(SettingData.PAYMENT_WAY_05)) {
                        handler.sendEmptyMessage(2);
                    }else if(payWay.equals(SettingData.PAYMENT_WAY_08)){
                        handler.sendEmptyMessage(6);
                    }
                } else {
                    String errorMsg = obj.getString("error_msg");
                    Message msg = Message.obtain();
                    msg.what = 8;
                    msg.obj = errorMsg;
                    Log.v("zyl","errorMsg:"+errorMsg);
                    if(errorMsg.contains("token")){

                        goToLogin.setGoToLogin();
                    }else{
                        handler.sendMessage(msg);
                    }
                    Log.v("zyl", "订单支付失败:" + obj.getString("error_msg"));
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(7);
                e.printStackTrace();
            }
        }
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //支付宝支付
                case 1:
                    AlipayModel model = (AlipayModel) msg.obj;

                    new Alipay((Activity) mContext, model, PayUtil.this).pay();
                    break;
                //余额支付成功
                case 2:
                    dismissProgressDialog();
                    Toast.makeText(mContext, "支付成功！", Toast.LENGTH_LONG).show();
                    new QueryInfo().start();
                    if (mContext instanceof Activity) {
                        ((Activity) mContext).finish();
                    }
                    Log.v("zyl","return_url:"+return_url);
                    EventBus.getDefault().post(new CouponGoCashBean(1));
                    EventBus.getDefault().post(new EventBusBean(211,return_url));
                    break;
                //刷新余额成功
                case 3:
                    if(tv_yuer!=null)
                    tv_yuer.setText(Stores.cash_balance + "");
                    break;

                //生成微信支付订单成功，调用给微信支付
                case 4:
                    Log.v("zyl", "开启微信支付界面");
                    WXOrderbean wxOrderbean = (WXOrderbean) msg.obj;
                    if (wxOrderbean != null) {
                        WetchatPay wetchatPay = new WetchatPay((Activity) mContext, wxOrderbean);
                        wetchatPay.pay();
                    }
                    break;
                case 5:
                    dismissProgressDialog();
                    Toast.makeText(mContext, "微信支付失败,网络波动", Toast.LENGTH_SHORT).show();
                    break;
                //金币支付
                case 6:
                    dismissProgressDialog();
                    Toast.makeText(mContext, "金币支付成功,订单已生成！", Toast.LENGTH_LONG).show();
                    new QueryInfo().start();
                    Intent intent2 = new Intent (mContext,TheOrderActivity.class);
                    intent2.putExtra("showFragmentIndex","1");
                    mContext.startActivity(intent2);
                    ((Activity)mContext).finish();
                    break;

                case 9:
                    dismissProgressDialog();
                    Toast.makeText(mContext, "微信支付失败,网络不通", Toast.LENGTH_SHORT).show();
                    break;
                case 7:
//                    goBackToHYD("2",tid,payment_id);
                    Toast.makeText(mContext, "支付失败，请检查本地网络", Toast.LENGTH_SHORT).show();
                    dismissProgressDialog();
                    break;
                //订单支付失败
                case 8:
                    dismissProgressDialog();
                    Toast.makeText(mContext, msg.obj.toString(), Toast.LENGTH_SHORT).show();


                    EventBus.getDefault().post(new EventBusBean(211, return_url + "?is_success=F"));
                    break;
            }
        }
    };


    public class QueryInfo extends Thread {
        public QueryInfo() {

        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token",
                        MainActivity.app_token));
                JSONObject paramsone = new JSONObject();
//						paramsone.put("member_id", MainActivity.member_id);
                paramsone.put("member_id", MainActivity.member_id + "");
                params.add(new BasicNameValuePair("params", paramsone
                        .toString()));
                params.add(new BasicNameValuePair("service",
                        "finance.memberAssetFind"));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/finance");

                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "查询余额信息成功:" + obj.getString("data"));
                    JSONObject jsonObject = new JSONObject(obj.getString("data"));
                    int vo = Integer.parseInt(jsonObject.getString("voucher_balance"));
                    double banlance = Double.parseDouble(jsonObject.getString("cash_balance"));
                    Stores.cash_balance = banlance;
                    Stores.voucher_balance = vo;
                    Stores.gold = jsonObject.getString("gold");
                    Log.v("zyl", "查询到的金币：" + Stores.gold);
                    Log.v("zyl", "Stores.voucher_balance:" + Stores.voucher_balance);
                    handler.sendEmptyMessage(3);
                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    }
                    Log.v("zyl", "查询余额信息失败");
                }
            } catch (Exception e) {
                Log.v("zyl", "网络不通");
            }
        }
    }

    private volatile ProgressDialog mProgressDialog;

    protected void showProgressDialog(String title, String msg, boolean ifCancel) {
        if (mProgressDialog == null || !mProgressDialog.getContext().equals(this)) {
            mProgressDialog = new ProgressDialog(mContext);
        }
        if (!TextUtils.isEmpty(title)) {
            mProgressDialog.setTitle(title);
        }
        mProgressDialog.setMessage(msg);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(ifCancel);
        mProgressDialog.show();
    }

    protected void dismissProgressDialog() {
        try {
            if (mProgressDialog != null)
                mProgressDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("zyl", "惠一丁发送微信广播");
            if(!TextUtils.isEmpty(return_url)){
                EventBus.getDefault().post(new EventBusBean(211,return_url));
            }
        }
    }
}
